﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using Medianamik.Core.Logging;
using Medianamik.Core.Profile;

namespace Medianamik.Core.Security
{
    public class LoginService
    {
        public static bool UserIsValid(string userName, out string ErrorMessage)
        {
            var user = Membership.GetUser(userName, false);

            if (user == null)
            {
                ErrorMessage = "Login_InvalidCredentials";
                return false;
            }

            if (!user.IsApproved)
            {
                ErrorMessage = "Login_UserNotApproved";
                return false;
            }

            if (user.IsLockedOut)
            {
                ErrorMessage = "Login_UserLockedOutError";
                return false;
            }

            var profile = (UserProfile)UserProfile.Create(userName, false);

            if (profile.ExpirationDate.HasValue
                && profile.ExpirationDate.Value < DateTime.Today)
            {
                ErrorMessage = "Login_UserExpiredError";
                return false;
            }

            ErrorMessage = String.Empty;
            return true;
        }

        public static void SetProfileLastActivity(string profileUsername)
        {
            var profile = (UserProfile)UserProfile.Create(profileUsername);

            if (profile != null && !profile.IsAnonymous)
            {
                var logger = new ActivityLogger();
                logger.Log(new LoggableObject("ConnectionSuccess", LogEntryType.Login), 
                    string.Empty, profile.UserName);

                profile.LastLoginDate = DateTime.Now;
                profile.Save();
            }
        }
    }
}
